'use strict';

const Controller = require('egg').Controller;

class DictTypeController extends Controller {
  async index(){
    const {ctx} = this;
    let option = ctx.helper.formatOptions(ctx.query,["dictType","dictName","status"]);
    try {
      let result = await ctx.model.SysDictType.findAndCountAll(option);
      ctx.body = ctx.helper.formateResponseList(result);
    } catch (error) {
      ctx.body = ctx.helper.formateResponse(null,"查询失败",310)
    }
  }
  async show(){
    const {ctx} = this;
    const {id} = ctx.params;
    try {
      const result = await ctx.model.SysDictType.findByPk(Number(id));
      ctx.body = ctx.helper.formateResponse(result);
    } catch (error) {
      
    }
  }
  async create(){
    const {ctx} = this;
    const dictType = ctx.request.body;
    const user = ctx.session.userinfo;
    const result = await ctx.model.SysDictType.findOne({
      where:{
        dictType:dictType.dictType
      }
    });
    if(!result){
      const _dict = Object.assign({},dictType,{createBy:user.userName,updateBy:user.userName});
      const data = await ctx.model.SysDictType.create(_dict);
      ctx.body = ctx.helper.formateResponse(data);
    }else{
      ctx.body = ctx.helper.formateResponse(null,500,"字典类型重复");
    }
    
  }
  async edit(){
    this.ctx.body = "edit";
  }
  // update
  async update(){
    const {ctx} = this;
    const data = ctx.request.body;
    const result = await ctx.model.SysDictType.findByPk(Number(data.dictId));
    if(!result) return ctx.body = ctx.helper.formateResponse(null,500,"修改失败");
    const user = ctx.session.userinfo;
    result.update({
      status:data.status,
      dictName:data.dictName,
      dictType:data.dictType,
      remark:data.remark,
      updateBy:user.userName
    });
    ctx.body = ctx.helper.formateResponse(result);
  }
  // delete
  async destroy(){
    const ctx = this.ctx;
    const id = ctx.params.id;
    const result = await ctx.model.SysDictType.findByPk(Number(id));
    if(result){
      await result.destroy();
      await ctx.service.dict.deleteByDictType(result.toJSON().dictType);
    }else{
      ctx.body = ctx.helper.formateResponse(null,500,"删除失败");
      return
    }
    ctx.body = ctx.helper.formateResponse(null);
  }
  async clearCache(){
    this.ctx.body = this.ctx.helper.formateResponse(null);
  }
}

module.exports = DictTypeController;
